package dep.dao.impl;

import dep.domain.User;
import dep.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

public class UserDaoImpl implements UserDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    /*
    * 查找用户是否存在
    * */
    @Override
    public User findByUsername(String username) {
        User user = null;
       try {
           String sql = "select * from tab_user where username = ?";
           user = template.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), username);
       }catch (Exception e){

       }
        return user;
    }
    /*
    * 保存注册信息到数据库
    * */

    @Override
    public void Save(User user) {
        String sql = "insert into tab_user(username,password,email,status,code) values(?,?,?,?,?)";
        template.update(sql,
                user.getUsername(),
                user.getPassword(),
                user.getEmail(),
                user.getStatus(),
                user.getCode());

    }

    /*
    * 根据激活码查找用户
    * */
    @Override
    public User findByCode(String code) {
        User user = null;
        try{
            String sql = "select * from tab_user where code = ?";
            user = template.queryForObject(sql,new BeanPropertyRowMapper<>(User.class),code);
        }catch (Exception e){
            e.printStackTrace();
        }
        return user;
    }
    /***
     * 修改指定用户激活状态
     */
    @Override
    public void updateStatus(User user) {
        String sql = "update tab_user set status = 'Y' where uid = ?";
        template.update(sql,user.getUid());
    }
    /**
     * 根据账号密码查询用户
     * */
    @Override
    public User findByUsernameAndPwd(String username, String password) {
        User user = null;
        try {
            String sql = "select * from tab_user where username = ? and password = ?";
            user = template.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), username,password);
        }catch (Exception e){

        }
        return user;
    }
}
